#!/usr/bin/env python

import sys
import tempfile
import os
import re

dateThreadRe = re.compile(r'[0-9][0-9][0-9][0-9][-.][0-9][0-9][-.][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9][.,][0-9][0-9][0-9] +([[(][^]]+[])]) ')
clientTicketJunkRe = re.compile(r'(Ticket is valid for|the client time is ahead of the server by|the client time is behind the server by|set clientTimeOffset to) [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+')

def numericThread(thread):
    for c in thread[1:-1]:
        if c not in '0123456789':
            return False
    return True
        
def removeJunk(lines, threadHash):
    line = lines.readline()
    while line:
        match = dateThreadRe.search(line)
        if match:
            thread = match.group(1)
            if numericThread(thread):
                if thread not in threadHash:
                    newThreadName = '[Thread' + str(len(threadHash)+1) + ']'
                    threadHash[thread] = newThreadName
                thread = threadHash[thread]
            line =  dateThreadRe.sub(thread + ' ', line)
        yield clientTicketJunkRe.sub('', line)
        line = lines.readline()


def main(args=None):
    if args == None:
        args = sys.argv[1:]


    fileName1 = args[0]
    fileName2 = args[1]

    (tempFile1, tempFileName1) = tempfile.mkstemp(os.path.basename(fileName1.replace(' ', '')))
    (tempFile2, tempFileName2) = tempfile.mkstemp(os.path.basename(fileName2.replace(' ', '')))

    tempFile1 = os.fdopen(tempFile1, 'wb')
    file1ThreadHash = {}
    for line in removeJunk(file(fileName1), file1ThreadHash):
        tempFile1.write(line)
    tempFile1.close()


    tempFile2 = os.fdopen(tempFile2, 'wb')
    file2ThreadHash = {}
    for line in removeJunk(file(fileName2), file2ThreadHash):
        tempFile2.write(line)
    tempFile2.close()
      
    # os.spawnl(os.P_WAIT, 'compare', 'c:\\Program Files\\Araxis\\Araxis Merge 2001 Professional\\compare.exe', tempFileName1, tempFileName2)

    #print 'compare ' + tempFileName1 + ' ' + tempFileName2
    os.popen('compare ' + tempFileName1 + ' ' + tempFileName2)
    #os.remove(tempFileName1)
    #os.remove(tempFileName2)

    
    return 0


if __name__ == '__main__':
    sys.exit(main())

